import os
import random
import string

from django.conf import settings
from urllib3.connectionpool import xrange


class UploadService():
    """
    文件上传服务类
    """

    # 文件上传
    def store(self, file, path=None, static='public/', origin=None, disName=None):
        # 没有文件放回false
        if not file:
            return False
        # 定义返回字典
        ret = dict()
        ret["size"] = file.size
        ret["originName"] = file.name
        # 处理保存的路径
        if not path:
            path = "uploads/"
            re_path = static + "uploads/"
        else:
            re_path = static + path
        # 本地上传
        if not disName:
            # 判断是否保留原文件名
            if not origin:
                name = self.randomString(16)
            else:
                name = file.name.split('.')[0]
            ret["name"] = file.name
            # 获取文件后缀名
            postfix = file.name.split('.')[1]
            # 若目录不存在则创建
            dir = os.path.join(settings.BASE_DIR, re_path)
            if not os.path.exists(dir): os.mkdir(dir)
            # 设置本地文件路径
            file_path = os.path.join(settings.BASE_DIR, re_path + name + '.' + postfix)
            # 将上传的文件写入本地目录
            f = open(file_path, "wb")
            for chunk in file.chunks():
                f.write(chunk)
            f.close()
            ret["fix"] = postfix
            # 返回路径
            ret["url"] = '/static/'+path + name + '.' + postfix
        # 返回结果
        return ret

    # 生成随机字符串
    def randomString(self, len):
        random_list = []
        for i in xrange(len):
            random_list.append(random.choice(string.ascii_letters + string.digits))
        return ''.join(random_list)